package com.example.graduation.service;

import com.example.graduation.dao.UserMapper;
import com.example.graduation.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    // 创建用户（新增）
    public User createUser(User user) {
        // 基础校验
        if (!StringUtils.hasText(user.getUsername())) {
            throw new IllegalArgumentException("用户名不能为空");
        }
        if (!StringUtils.hasText(user.getEmail())) {
            throw new IllegalArgumentException("邮箱不能为空");
        }
        if (!StringUtils.hasText(user.getPassword())) {
            throw new IllegalArgumentException("密码不能为空");
        }

        // 检查邮箱是否已存在
        if (userMapper.findByEmail(user.getEmail()) != null) {
            throw new IllegalStateException("邮箱已被注册");
        }

        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userMapper.insertUser(user);
        return user;
    }

    // 获取所有用户
    public List<User> getAllUsers() {
        return userMapper.findAll();
    }

    // 根据ID获取用户
    public User getUserById(Integer id) {
        return userMapper.findById(id);
    }

    // 更新用户
    public void updateUser(User user) {
        if (user.getId() == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }

        User existingUser = userMapper.findById(user.getId());
        if (existingUser == null) {
            throw new IllegalArgumentException("用户不存在");
        }

        // 直接复制所有字段（无论是否为空）
        existingUser.setUsername(user.getUsername());  // 允许覆盖为空字符串
        existingUser.setName(user.getName());          // 允许从 NULL 更新为 "张三"
        existingUser.setGender(user.getGender());
        existingUser.setAge(user.getAge());
        existingUser.setMajor(user.getMajor());
        existingUser.setPhone(user.getPhone());
        existingUser.setRole(user.getRole());
        existingUser.setEmail(user.getEmail());


        // 邮箱更新逻辑
        if (user.getEmail() != null) {
            String newEmail = user.getEmail();
            if (!newEmail.equals(existingUser.getEmail())) {
                if (userMapper.findByEmail(newEmail) != null) {
                    throw new IllegalStateException("邮箱已被注册");
                }
                existingUser.setEmail(newEmail);
            }
        }

        // 密码更新（仅在非空时加密）
        if (user.getPassword() != null) {
            existingUser.setPassword(passwordEncoder.encode(user.getPassword()));
        }

        userMapper.update(existingUser);
    }
    // 删除用户
    public void deleteUser(Integer id) {
        userMapper.delete(id);
    }
}